package com.ch.mobilesha.net;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.LinkedHashMap;
import java.util.Map.Entry;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;

import com.ch.mobilesha.common.CommonData;
import com.ch.mobilesha.common.HttpClientUtils;
import com.ch.mobilesha.tools.UtilLog;
import com.ch.mobilesha.tools.UtilTools;

public class NetManager {

	public static final String key = "";
	private static final String URL_HEAD = "";

	public static final String UPLOAD_IMAGE_URL = "agentupload";// 上传图片的地址

	/**
	 * get方式获取网络请求
	 * 
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static InputStream handleGetRequest(String url) throws Exception {
		url = URL_HEAD + url;
		UtilLog.e("url", url);
		try {
			HttpGet httpGet = new HttpGet(url);
			HttpResponse response = HttpClientUtils.getHttpClient().execute(
					httpGet);
			switch (response.getStatusLine().getStatusCode()) {
			case HttpStatus.SC_OK:
				if (CommonData.isTest) {
					InputStream is = response.getEntity().getContent();
					try {
						BufferedReader in = new BufferedReader(
								new InputStreamReader(is));
						String str = "";
						StringBuffer s = new StringBuffer("");
						while ((str = in.readLine()) != null) {
							s.append(str);
						}
						UtilLog.e("url", "" + s.toString());
						if (is != null) {
							is.close();
						}
						if (in != null) {
							in.close();
						}
					} catch (Exception e) {
						
					}
					
					return response.getEntity().getContent();
				} else {
					return response.getEntity().getContent();
				}

			default:
				httpGet.abort();
				return null;
			}
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * post方式获取网络请求
	 * 
	 * @param url
	 * @throws Exception
	 */
	public static InputStream handlePostRequest(String url) throws Exception {
		try {
			HttpPost httpPost = new HttpPost(url);
			HttpResponse response = HttpClientUtils.getHttpClient().execute(
					httpPost);
			switch (response.getStatusLine().getStatusCode()) {
			case HttpStatus.SC_OK:
				if (CommonData.isTest) {
					InputStream is = response.getEntity().getContent();
					BufferedReader in = new BufferedReader(
							new InputStreamReader(is));
					String str = "";
					StringBuffer s = new StringBuffer("");
					while ((str = in.readLine()) != null) {
						s.append(str);
					}
					UtilLog.e("url", "" + s.toString());
					if (is != null) {
						is.close();
					}
					if (in != null) {
						in.close();
					}
					return response.getEntity().getContent();
				} else {
					return response.getEntity().getContent();
				}

			default:
				httpPost.abort();
				return null;
			}
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 上传图片
	 * 
	 * @param filePath
	 *            图片的本地路径
	 * @param username
	 *            图片名
	 * @return
	 */
	public static String uploadFile(String filePath, String username) {
		byte[] dataName = null;
		try {
			dataName = username.getBytes("UTF-8");
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		int lengthName = dataName.length;
		byte[] dataLength = UtilTools.intToByte(lengthName);
		String result = null;
		BufferedReader rd = null;
		URL u = null;
		URLConnection conn = null;
		OutputStream os = null;
		try {
			u = new URL(UPLOAD_IMAGE_URL);
			conn = u.openConnection();
			conn.setReadTimeout(15 * 1000);
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			if (filePath != null) {
				os = conn.getOutputStream();
				os.write(dataLength);
				os.write(dataName);
			}
			FileInputStream fis = new FileInputStream(filePath);
			byte[] buffer = new byte[4096];
			int length = -1;

			while ((length = fis.read(buffer)) != -1) {
				os.write(buffer, 0, length);
			}

			rd = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), "UTF-8"));
			StringBuffer strBuffer = new StringBuffer();
			String rn = System.getProperty("line.separator");
			while ((result = rd.readLine()) != null) {
				strBuffer.append(result + rn);
			}
			result = strBuffer.toString();
			strBuffer.delete(0, strBuffer.length());
			if (fis != null)
				fis.close();
			if (rd != null)
				rd.close();
			if (os != null)
				os.close();
			conn = null;
			u = null;
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (result != null) {
			result = result.replaceAll("<.*?>", "").trim();
			result = result.replaceAll("[%]amp", "&");
		}
		return result;

	}

	/**
	 * 构建url
	 * 
	 * @param methodName
	 * @param params
	 * @return
	 */
	public static String buildUrl(String methodName,
			LinkedHashMap<String, String> params) {
		StringBuilder sb = new StringBuilder();
		sb.append(methodName);
		if (params != null && params.size() > 0) {
			sb.append("?");
			for (Entry<String, String> entry : params.entrySet()) {
				sb.append(entry.getKey()).append("=").append(entry.getValue())
						.append("&");
			}
			sb.deleteCharAt(sb.length() - 1);
		}
		return sb.toString();
	}

	public static String getKey(String userid, String value) {
		String md5String = "";
		String md5Temp = "";
		String returnValue = "";
		if (userid == null || userid.equals("0") || userid.equals("")) {
			md5Temp = getMD5Str("0" + "SOUFUN");
		} else {
			md5Temp = getMD5Str(userid + "SOUFUN");
		}
		if (value == null || value.equals("")) {
			md5String = getMD5Str(key + md5Temp);
		} else {
			md5String = getMD5Str(key + md5Temp + value);
		}
		if (userid == null || userid.equals("0") || userid.equals("")) {
			returnValue = "key=" + md5String;
		} else {
			returnValue = "key=" + md5String + "&loggedNow=" + userid;
		}
		return returnValue;
	}

	public static String getMD5Str(String str) {
		MessageDigest messageDigest = null;
		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(str.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException e) {
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		byte[] byteArray = messageDigest.digest();
		StringBuffer md5StrBuff = new StringBuffer();
		for (int i = 0; i < byteArray.length; i++) {
			if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
				md5StrBuff.append("0").append(
						Integer.toHexString(0xFF & byteArray[i]));
			else
				md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
		}
		return md5StrBuff.toString().toLowerCase();
	}
}
